package de.mindshareprojects.datawarehouse.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import de.mindshareprojects.datawarehouse.client.DataService;
import de.mindshareprojects.datawarehouse.shared.Advertiser;
import de.mindshareprojects.datawarehouse.shared.Campaign;
import de.mindshareprojects.datawarehouse.shared.WebAnalyticsLineItem;

@SuppressWarnings("serial")
public class DataServiceImpl extends RemoteServiceServlet implements DataService {
	
	static StringBuffer response = new StringBuffer();
	
	PersistenceManager pm = PMF.get().getPersistenceManager();

	private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

	@Override
	public Campaign createCampaign(Campaign campaign) throws IllegalArgumentException{

		try {
			pm.makePersistent(campaign);
			
		} catch (Exception e) {
			System.out.println("Failure while trying to make Campaign persistent.");
		}
		return campaign;
	}

	
	@Override
	public Advertiser createAdvertiser(Advertiser advertiser)
			throws IllegalArgumentException {
		try {
			pm.makePersistent(advertiser);
			
		} catch (Exception e) {
			System.out.println("Failure while trying to make Advertiser persistent.");
			e.printStackTrace();
		}
		return advertiser;
	}
	
	//#########################################################################################
	@Override
	public WebAnalyticsLineItem createWebAnalyticsLineItem(WebAnalyticsLineItem webAnalyticsLineItem) throws IllegalArgumentException {

		try {
			pm.makePersistent(webAnalyticsLineItem);
			
		} catch (Exception e) {
			System.out.println("Failure while trying to make WebAnalyticsLineItem persistent.");
		}
		return webAnalyticsLineItem;
	}
	//########################################################################################
	
	/** 
	 * @gwt.typeArgs <Advertiser>
	 */
	public ArrayList<Advertiser> getAdvertisers() {
		List<Advertiser> advertiserList = null;
		ArrayList<Advertiser> result = new ArrayList<Advertiser>();
		Query query = pm.newQuery(Advertiser.class);
		try{
			advertiserList = (List<Advertiser>) query.execute();
			System.out.println("Succesful query: Advertiser.");
			System.out.println("Number of elements: " + advertiserList.size());
			for (Advertiser a: advertiserList){
				result.add(a);
			}
			
			
		} catch (Exception e) {
			System.out.println("Error while trying to query Advertisers.");
		}		
		return result;
	}
//############################################# Get Advertisers to AdvertiserID ########################
	/** 
	 * @gwt.typeArgs <Advertiser>
	 */

	public Advertiser getAdvertiser(Long advertiserKey) {
		Advertiser advertiser = null;
		
		try{
			advertiser = pm.getObjectById(Advertiser.class, advertiserKey);
			System.out.println("Succesful query: Advertiser " + advertiserKey);
			
			
		} catch (Exception e) {
			System.out.println("Error while trying to query Advertiser " + advertiserKey);
		}		
		return advertiser;
	}
// #####################################################################################################
	
	/** 
	 * @gwt.typeArgs <Campaign>
	 */

	public ArrayList<Campaign> getCampaigns() {
		List<Campaign> campaignList = null;
		ArrayList<Campaign> result = new ArrayList<Campaign>();
		Query query = pm.newQuery(Campaign.class);
		try{
			campaignList = (List<Campaign>) query.execute();
			System.out.println("Succesful query: Campaign. Number of elements:" + campaignList.size());
			for (Campaign c: campaignList){
				result.add(c);
			}
			
			
		} catch (Exception e) {
			System.out.println("Error while trying to query Campaings.");
			
		}		
		return result;
	}

	/** 
	 * @gwt.typeArgs <Campaign>
	 */

	public ArrayList<Campaign> getCampaignsByCountry(String country) {
		List<Campaign> campaignList = null;
		ArrayList<Campaign> result = new ArrayList<Campaign>();
		Query query = pm.newQuery(Campaign.class);
		query.setFilter("country == countryParam");
		query.declareParameters("String countryParam");
		try{
			campaignList = (List<Campaign>) query.execute(country);
			System.out.println("Succesful query: Campaign.");
			System.out.println("Number of elements:" + campaignList.size());
			for (Campaign c: campaignList){
				result.add(c);
			}
			
			
		} catch (Exception e) {
			System.out.println("Error while trying to query Campaings.");
			
		}		
		return result;
	}
//########################################################## Get Campaigns nach AdvertiserID ####################################################

	/** 
	 * @gwt.typeArgs <Campaign>
	 */

	public ArrayList<Campaign> getCampaignsByAdvertiser(Long advertiserKey) {
		System.out.println("Advertiser ID fuer die Suche="+advertiserKey);
		List<Campaign> campaignList = null;
		ArrayList<Campaign> result = new ArrayList<Campaign>();	
		Query query = pm.newQuery(Campaign.class);
		query.setFilter("key==advertiserKey");
		query.declareParameters("String advertiserKey");
		try{
			campaignList = (List<Campaign>) query.execute(advertiserKey);
			System.out.println("Succesful query: Campaign.");
			System.out.println("Number of elements:" + campaignList.size());
			for (Campaign c: campaignList){
				result.add(c);
			}
			
			
		} catch (Exception e) {
			System.out.println("Error while trying to query Campaings by AdvertiserID.");
			
		}		
		return result;
	}
	
//###############################################################################################################################################	
	

	
	/** 
	 * @gwt.typeArgs <WebAnalyticsLineItem>
	 */
	public ArrayList<WebAnalyticsLineItem> getWebAnalyticsLineItemsByAdvertiserGroup(Long groupKey) {
		List<WebAnalyticsLineItem> webAnalyticsLineItemList = null;
		ArrayList<WebAnalyticsLineItem> result = new ArrayList<WebAnalyticsLineItem>();
		Query query = pm.newQuery(WebAnalyticsLineItem.class);
		query.setFilter("advertiserGroupKey==advertiserGroupKeyParam");
		query.declareParameters("Long advertiserGroupKeyParam");
		try{
			webAnalyticsLineItemList = (List<WebAnalyticsLineItem>) query.execute(groupKey);
			System.out.println("Succesful query: Advertiser.");
			System.out.println("Number of elements: " + webAnalyticsLineItemList.size());
			for (WebAnalyticsLineItem a: webAnalyticsLineItemList){
				result.add(a);
			}
			
			
		} catch (Exception e) {
			System.out.println("Error while trying to query WebAnalyticsLineItem.");
		}		
		return result;
	}	

	/** 
	 * @gwt.typeArgs <WebAnalyticsLineItem>
	 */
	public ArrayList<WebAnalyticsLineItem> getWebAnalyticsLineItems() {
		List<WebAnalyticsLineItem> webAnalyticsLineItemList = null;
		ArrayList<WebAnalyticsLineItem> result = new ArrayList<WebAnalyticsLineItem>();
		Query query = pm.newQuery(WebAnalyticsLineItem.class);
		try{
			webAnalyticsLineItemList = (List<WebAnalyticsLineItem>) query.execute();
			System.out.println("Succesful query: Advertiser.");
			System.out.println("Number of elements: " + webAnalyticsLineItemList.size());
			for (WebAnalyticsLineItem a: webAnalyticsLineItemList){
				result.add(a);
			}
			
			
		} catch (Exception e) {
			System.out.println("Error while trying to query WebAnalyticsLineItem.");
		}		
		return result;
	}	
	
	/** 
	 * @gwt.typeArgs <Boolean>
	 */
	public Boolean checkIfLineItemsExist(Long campaignKey) {
		Boolean result = null;
		List<WebAnalyticsLineItem> webAnalyticsLineItemList = null;
		Query query = pm.newQuery(WebAnalyticsLineItem.class, "campaignKey == campaignKeyParam");
		query.declareParameters("Long campaignKeyParam");
		query.setRange(0, 5);
		try{
			webAnalyticsLineItemList = (List<WebAnalyticsLineItem>) query.execute(campaignKey);
			System.out.println("Number of elements queried: " + webAnalyticsLineItemList.size());
			if(webAnalyticsLineItemList.size() > 0){
				result = true;
			} else {
				result = false;
			}
			
		} catch (Exception e) {
			System.out.println("Error while trying to query WebAnalyticsLineItem.");
			e.printStackTrace();
		}		
		return result;
	}
	
	/** 
	 * @gwt.typeArgs <Boolean>
	 */
	public Boolean deleteCampaignItems(Long campaignKey) {
		Boolean result = null;
		
		Query query = pm.newQuery(WebAnalyticsLineItem.class, "campaignKey == campaignKeyParam");
		query.declareParameters("Long campaignKeyParam");
		try{
			query.deletePersistentAll(campaignKey);
			System.out.println("All campaign elements deleted.");
			result = true;
			
			
		} catch (Exception e) {
			System.out.println("Error while trying to delete WebAnalyticsLineItems.");
			e.printStackTrace();
			result = false;
		}		
		return result;
	}
	/** 
	 * @gwt.typeArgs <WebAnalyticsLineItem>
	 */
	public Boolean saveAllWebAnalyticsLineItems(ArrayList<WebAnalyticsLineItem> itemsToSave){
		try {
			pm.makePersistentAll(itemsToSave);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
		
	}

	/** 
	 * @gwt.typeArgs <Advertiser>
	 */

	@Override
	public Boolean saveAllAdvertisers(ArrayList<Advertiser> itemsToSave) {
		try {
			pm.makePersistentAll(itemsToSave);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
	
	/** 
	 * @gwt.typeArgs <Campaign>
	 */

	@Override
	public Boolean saveAllCampaigns(ArrayList<Campaign> itemsToSave) {
		try {
			pm.makePersistentAll(itemsToSave);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}

	/** 
	 * @gwt.typeArgs <Campaign>
	 */

	@Override
	public ArrayList<Campaign> getCampaignsByAdvertiserGroup(Long groupKey, String country) {
		
		List<Campaign> campaignList = null;
		ArrayList<Campaign> result = new ArrayList<Campaign>();	
		List<Advertiser> advertiserList = null;
		ArrayList<Advertiser> tempAdvertisers = new ArrayList<Advertiser>();	
		
		// get advertisers in group
		Query queryAdvertisers = pm.newQuery(Advertiser.class);
		queryAdvertisers.setFilter("advertiserGroupKey==groupKeyParam && country==countryParam");
		queryAdvertisers.declareParameters("Long groupKeyParam, String countryParam");
		try{
			advertiserList = (List<Advertiser>) queryAdvertisers.execute(groupKey, country);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		Query queryCampaigns = pm.newQuery(Campaign.class);
		queryCampaigns.setFilter("advertiserId==advertiserKey");
		queryCampaigns.declareParameters("Long advertiserKey");

		for(Advertiser a: advertiserList){
			
			try{
				campaignList = (List<Campaign>) queryCampaigns.execute(a.getKey());
				for (Campaign c: campaignList){
					result.add(c);
				}
				
				
			} catch (Exception e) {
				System.out.println("Error while trying to query Campaings by AdvertiserID.");
				
			}		
		}
		
		return result;
	}


	@Override
	public Boolean saveAdvertiser(Advertiser advertiser) {
		Boolean result = false;
		try {
			pm.makePersistent(advertiser);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}


	@Override
	public ArrayList<Advertiser> getWebAnalyticsAdvertisers() {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public ArrayList<Advertiser> getAdvertisersByCountry(String country) {
		List<Advertiser> advertiserList = null;
		ArrayList<Advertiser> result = new ArrayList<Advertiser>();
		
		Query queryAdvertisers = pm.newQuery(Advertiser.class);
		queryAdvertisers.setFilter("country==countryParam");
		queryAdvertisers.declareParameters("String countryParam");
		try{
			advertiserList = (List<Advertiser>) queryAdvertisers.execute(country);
			for(Advertiser a: advertiserList){
				result.add(a);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return result;
	}


	@Override
	public String getUploadURL(String urlRedirect) {
		
		String url = blobstoreService.createUploadUrl(urlRedirect);
		System.out.println(url);
		return url;
	}
}




